<template>
  <div ref="lookContainer" class="look-container">
    <FilterTree
      :treeData="paramTree"
      :initialRootArray="initialRootArray"
      @updateParams="updateParams"
      :searchPlaceholder="'请输入搭配名称/款号搜索'"
      @updateSearchText="updateSearchText"
    ></FilterTree>
    <div class="table-page-search-wrapper" v-if="isBox">
      <a-form layout="inline">
        <a-row :gutter="16">
          <a-col :xl="8" :lg="12" :sm="24">
            <a-form-item label="排序" required>
              <a-select v-model="queryParam.sortType" placeholder="请选择" :getPopupContainer="triggerNode => triggerNode.parentNode" @change="searchList">
                <a-select-option :value="1">按时间</a-select-option>
                <a-select-option :value="3">按评级</a-select-option>
                <!-- <a-select-option :value="3">综合</a-select-option> -->
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :xl="8" :lg="12" :sm="24">
            <a-form-item label="来源" required>
              <a-select v-model="queryParam.source" placeholder="请选择" :getPopupContainer="triggerNode => triggerNode.parentNode" @change="searchList">
                <a-select-option value="BOX">有搭</a-select-option>
                <a-select-option value="OTHER">企划</a-select-option>
                <a-select-option value="BOX,OTHER">不限</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :xl="8" :lg="12" :sm="24">
            <a-form-item label="波段">
              <a-tooltip>
                <template slot="title" v-if="queryParam.bands && queryParam.bands.length > 3">
                  <!-- {{ bandsName(queryParam.bands, bandsList) }} -->
                  {{ queryParam.bands.join(',') }}
                </template>

                <a-select
                  mode="multiple"
                  :maxTagCount="3"
                  autoClearSearchValue
                  show-search
                  allowClear
                  v-model="queryParam.bands"
                  placeholder="请选择波段"
                  :filter-option="filterOption"
                  @change="searchList"
                >
                  <a-select-option v-for="(item, index) in bandsList" :key="index" :value="item.attribname">{{ item.attribname }}</a-select-option>
                </a-select>
              </a-tooltip>
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </div>
    <a-divider dashed style="margin-top: 12px" />
    <!-- 商品列表 -->
    <div class="ant-pro-pages-list-projects-cardList">
      <a-list :loading="loading" :data-source="lookList" :grid="{ gutter: 0 }">
        <a-list-item slot="renderItem" slot-scope="item">
          <a-card class="ant-pro-pages-list-projects-card" hoverable>
            <div class="gallery">
              <img slot="cover" class="cover" v-lazy="item.coverImg" :alt="item.name" @click="openLookDetail(item)" v-if="item.coverImg" />
              <template v-else>
                <div class="four-imgs" @click="openLookDetail(item)">
                  <img :src="good.extend.productImage" v-for="good in thumbFourGoods(item.productList)" :key="good.id" alt="" />
                </div>
                <div class="vertical"></div>
                <div class="horizontal"></div>
              </template>
              <span class="rank rank-s" v-if="item.level == 10">S级</span>
              <span class="rank rank-a" v-if="item.level == 20">A级</span>
              <span class="rank rank-b" v-if="item.level == 30">B级</span>
              <img src="../../../assets/image/magnifier.png" alt="" class="magnifier" @click="openBigImg(item.galleryList)" />
              <div class="code">共{{ item.productList.length }}件</div>
            </div>
            <div class="thumb-content">
              <img :src="good.extend.productImage" v-for="good in thumbGoods(item.productList)" :key="good.id" alt="" @click="openDetail(good.productId)" class="thumb" />
            </div>
            <ellipsis :length="18" tooltip style="font-size: 14px;font-family: PingFangSC-Medium, PingFang SC;font-weight: 500;color: rgba(0, 0, 0, 0.85);margin-left:6px;">{{ item.name }}</ellipsis>
          </a-card>
        </a-list-item>
      </a-list>
      <p class="bottom-tip" v-show="showBottom && lookList.length > 0">
        <a-spin v-if="loadingMore" />
        <span v-else>没有更多啦</span>
      </p>
    </div>
    <!-- 商详 -->
    <GoodInfoModal ref="goodInfoModal" :modalWidth="isBox ? '60vw' : '80vw'"></GoodInfoModal>
    <!-- 大图 -->
    <BigImg :visibleImgs="visibleImgs" :imgList="imgList" @closeBig="closeBig"></BigImg>
    <!-- 推荐LOOK -->
    <recommend-look-draw
      ref="recommendLookDraw"
      :weid="weid"
      :storeId="storeId"
      :storeIdByLink="storeIdByLink"
      :unionId="unionId"
      :isBox="isBox"
      :isLookId="true"
      @sendProduct="sendProduct"
      @sendLook="sendLook"
      @refreshShoppingCart="updateShoppingCart"
    />
  </div>
</template>
<script>
import FilterTree from '@/views/box/components/FilterTree'
import GoodInfoModal from '../../../components/GoodInfoModal'
import BigImg from '@/views/box/components/UserMsg/bigImg'
import RecommendLookDraw from './RecommendLookDraw'
import { Ellipsis } from '@/views/box/components'
import { stylingList, stylingTags, queryDim } from '@/api/box/workbench'
export default {
  props: {
    unionId: {
      type: String,
      default: ''
    },
    isEmit: {
      // 是否调用外部方法
      type: Boolean,
      default: false
    },
    isBox: {
      // 是否为box使用
      type: Boolean,
      default: true,
      required: false
    },
    storeIdByLink: {
      type: [String, Number],
      default: null,
      required: false
    },
    weid: {
      type: [String, Number],
      default: null,
      required: false
    },
    // 微商城xcx品牌
    weBrand: {
      type: String,
      default: '',
      required: false
    },
    // 性别
    gender: {
      type: [String, Number],
      default: null,
      required: false
    }
  },
  components: {
    FilterTree,
    Ellipsis,
    GoodInfoModal,
    BigImg,
    RecommendLookDraw
  },
  data() {
    return {
      storeId: '',
      paramTree: [],
      initialRootArray: [],
      queryParam: {
        source: 'BOX,OTHER'
      },
      lookList: [],
      pageSize: 20,
      current: 1,
      total: 0,
      pages: 0,
      loading: true,
      loadingMore: true,
      showLoadingMore: false,
      showBottom: false,
      isRefreshBool: false,
      zipImg: '?imageView2/0/format/jpg/q/75',
      visibleImgs: false,
      imgList: [],
      yearsList: [],
      bandsList: []
    }
  },
  computed: {
    thumbGoods() {
      return list => {
        let newList = list.slice(0, 3)
        return newList
      }
    },
    thumbFourGoods() {
      return list => {
        let newList = list.slice(0, 4)
        return newList
      }
    },
    bandsName() {
      return (arr, list) => {
        if (arr && arr.length > 0) {
          let newList = []
          list.forEach(item => {
            arr.forEach(child => {
              if (child == item.id) {
                newList.push(item.attribname)
              }
            })
          })
          return newList.join('，')
        }
      }
    }
  },
  mounted() {
    if (this.isEmit) {
      window.addEventListener('scroll', this.handleDrawScroll, true)
    } else {
      window.addEventListener('scroll', this.handleScroll, true)
    }
    if (this.isBox) {
      this.queryParam.sortType = 1
      // this.queryParam.source = 3
    }
    this.getStylingTags()
    this.searchList()
  },
  destroyed() {
    if (this.isEmit) {
      window.removeEventListener('scroll', this.handleDrawScroll, true)
    } else {
      window.removeEventListener('scroll', this.handleScroll, true)
    }
  },
  methods: {
    filterOption(input, option) {
      return option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
    },
    // 获取标签
    getStylingTags() {
      queryDim()
        .then(res => {
          if (res.code === 0) {
            this.bandsList = res.data.bandsV2
          } else {
            this.$message.error(res.msg)
          }
        })
        .catch(err => {
          console.log('getSelectList:' + err)
        })
      stylingTags()
        .then(res => {
          if (res.code == 0) {
            // {code: "2", name: "JNBY", pid: "00020000", id: "00020001"}
            this.yearsList = res.data.years.map((e, i) => {
              return {
                code: e.code,
                name: e.name,
                pid: '00022000',
                id: '000' + (22001 + i)
              }
            })

            let styleList = res.data.styling.map((e, i) => {
              return {
                code: e.code,
                name: e.name,
                pid: '00020000',
                id: '000' + (20001 + i)
              }
            })
            let levelList = res.data.levels.map((e, i) => {
              return {
                code: e.code,
                name: e.name,
                pid: '00019000',
                id: '000' + (19001 + i)
              }
            })
            let sceneList = res.data.scene.map((e, i) => {
              return {
                code: e.code,
                name: e.name,
                pid: '00021000',
                id: '000' + (21001 + i)
              }
            })
            let season = res.data.season

            this.paramTree = [
              {
                children: [
                  {
                    code: '2',
                    name: 'JNBY',
                    pid: '00018000',
                    id: '00018001'
                  },
                  {
                    code: '5',
                    name: 'LESS',
                    pid: '00018000',
                    id: '00018002'
                  },
                  {
                    code: '3',
                    name: 'CROQUIS',
                    pid: '00018000',
                    id: '00018007'
                  },
                  {
                    code: '57',
                    name: 'A PERSONAL NOTE 73',
                    pid: '00018000',
                    id: '00018006'
                  },
                  {
                    code: '17',
                    name: 'JNBYHOME',
                    pid: '00018000',
                    id: '00018008'
                  },
                  {
                    code: '12',
                    name: 'POMME DE TERRE',
                    pid: '00018000',
                    id: '00018005'
                  },
                  {
                    code: '4',
                    name: '童装',
                    pid: '00018000',
                    id: '00018003'
                  },
                  {
                    code: '4',
                    name: '婴童',
                    pid: '00018000',
                    id: '00018004'
                  }
                ],
                name: '品牌',
                id: '00018000'
              },
              {
                children: levelList,
                id: '00019000',
                name: '评级'
              },
              {
                children: styleList,
                id: '00020000',
                name: '风格'
              },
              {
                children: sceneList,
                id: '00021000',
                name: '场景'
              },
              {
                children: this.yearsList,
                id: '00022000',
                name: '年份'
              },
              season
            ]
            for (let item of this.paramTree) {
              Object.assign(item, {
                isMuilt: true,
                isCustom: false,
                checkList: [],
                checkValue: [],
                radioValue: null
              })
              if (item.name == '场景' || item.name == '风格') {
                item.toggleNum = 7
                item.toggle = false
              }
            }
            // console.log(this.weBrand)
            // 初始化品牌
            this.initialBrandGender(this.paramTree)
          } else {
            this.$toast(res.msg)
          }
        })
        .catch(err => {
          console.log(err)
        })
    },
    // 初始化品牌
    initialBrandGender(list) {
      for (let item of list) {
        if (item.name == '品牌') {
          if (this.gender == 0) {
            item.checkValue = item.children.filter(e => e.code == '2') //2jnby 5less
          } else if (this.gender == 1) {
            item.checkValue = item.children.filter(e => e.code == '3') //3速写 57apn
          }
          // 微商城陪逛初始品牌
          if (this.weBrand != '') {
            item.checkValue = item.children.filter(e => e.code == this.weBrand) //3速写 57apn
          }
          if (item.checkValue.length > 0) item.checkList = item.checkValue.map(e => e.code)
        }
      }
      this.initialRootArray = []
      if (this.gender != null) {
        for (let item of list) {
          if (item.name == '品牌') {
            this.initialRootArray.push({
              checkValue: item.checkValue,
              title: item.name,
              names: item.checkValue.length > 0 ? item.checkValue.map(a => a.name) : [],
              codes: item.checkValue.length > 0 ? item.checkValue.map(a => a.code) : []
            })
          } else {
            this.initialRootArray.push({
              checkValue: [],
              title: item.name,
              names: [],
              codes: []
            })
          }
        }
      }
      // console.log(this.initialRootArray)
      this.updateParams(this.initialRootArray)
    },
    // 搜索列表
    searchList() {
      // window.scrollTo(0, 0)
      this.loading = true
      this.showBottom = false
      this.isRefreshBool = false
      this.current = 1
      this.lookList = []
      // console.log('searchList', this.queryParam)
      const param = JSON.parse(JSON.stringify(this.queryParam))
      param.source = this.queryParam.source.split(',')
      this.fetchList(param)
    },
    async fetchList(d) {
      try {
        const dataList = await this.getList(d)
        if (dataList.length > 0) {
          this.loading = false
          this.isRefreshBool = true
          this.concatList(dataList)
        } else {
          this.isRefreshBool = false
          this.loading = false
          this.showButtom = false
          this.loadingMore = false
        }
      } catch (err) {
        console.log(err)
      }
    },
    getList(d) {
      // console.log(d)
      let params = {
        page: {
          pageNo: this.current,
          pageSize: this.pageSize
        },
        requestData: d
      }
      return stylingList(params).then(res => {
        if (res.code === 0) {
          this.current = res.page.pageNo
          this.total = res.page.count
          this.pages = res.page.pages
          if (this.current == this.pages) {
            this.isRefreshBool = false
          }
          let data = res.data
          for (let item of data) {
            item.coverImg = item.galleryList && item.galleryList.length > 0 ? item.galleryList[0].url + this.zipImg : ''
            let list = JSON.parse(JSON.stringify(item.productList))
            item.productList = list.map(good => {
              return {
                ...good,
                extend: JSON.parse(good.extendJson)
              }
            })
          }

          if (this.current == 1) {
            this.lookList = []
          }
          return data
        } else {
          this.$message.error(res.msg)
        }
      })
    },
    concatList(dataList) {
      this.lookList = this.lookList.concat(dataList)
      if (this.current == this.pages) {
        this.loadingMore = false
        this.showBottom = true
      } else {
        this.showBottom = false
        this.loadingMore = true
      }
      if (this.lookList.length == 0) return

      this.$forceUpdate()
    },
    // 加载更多
    onLoadMore() {
      console.log('------onLoadMore-----')
      this.current = this.current + 1
      const param = JSON.parse(JSON.stringify(this.queryParam))
      param.source = this.queryParam.source.split(',')
      // console.log('onLoadMore', param)
      this.fetchList(param)
    },
    // 筛选条件
    updateParams(data) {
      let paramsArr = JSON.parse(JSON.stringify(data))
      // console.log(paramsArr)
      if (paramsArr.length > 0) {
        let brandItem = paramsArr.filter(e => e.title == '品牌')
        this.queryParam.brandIds = brandItem[0].codes

        let levelsItem = paramsArr.filter(e => e.title == '评级')
        this.queryParam.levels = levelsItem[0].codes

        let sceneItem = paramsArr.filter(e => e.title == '场景')
        let styleItem = paramsArr.filter(e => e.title == '风格')
        this.queryParam.labelIds = [...sceneItem[0].codes, ...styleItem[0].codes]

        let seasonItem = paramsArr.filter(e => e.title == '季节')
        this.queryParam.seasonIds = seasonItem[0].codes

        let yearItem = paramsArr.filter(e => e.title == '年份')
        this.queryParam.minYears = ''
        if (yearItem[0].codes.indexOf('其他') > -1) {
          this.queryParam.minYears = this.yearsList[4].code
        }
        this.queryParam.years = yearItem[0].codes.filter(e => e != '其他')

        this.searchList()
      }
    },
    updateSearchText(text) {
      this.queryParam.productCode = text
      this.searchList()
    },
    handleScroll() {
      //变量scrollTop是滚动条滚动时，距离顶部的距离
      var scrollTop = document.documentElement.scrollTop || document.body.scrollTop
      //变量windowHeight是可视区的高度
      var windowHeight = document.documentElement.clientHeight || document.body.clientHeight
      //变量scrollHeight是滚动条的总高度
      var scrollHeight = document.documentElement.scrollHeight || document.body.scrollHeight

      //滚动条到底部的条件
      if (scrollTop + windowHeight + 20 >= scrollHeight && this.isRefreshBool) {
        // console.log('距顶部' + scrollTop + '可视区高度' + windowHeight + '滚动条总高度' + scrollHeight)
        this.isRefreshBool = false
        this.showBottom = true
        if (this.current == this.pages) {
          this.loadingMore = false
        } else {
          this.loadingMore = true
          this.onLoadMore()
        }
      }
    },
    handleDrawScroll() {
      //变量scrollTop是滚动条滚动时，距离顶部的距离
      var scrollTop = this.$refs.lookContainer.scrollTop
      //变量windowHeight是可视区的高度
      var windowHeight = document.documentElement.clientHeight || document.body.clientHeight
      //变量scrollHeight是滚动条的总高度
      var scrollHeight = this.$refs.lookContainer.scrollHeight
      // 元素位置
      var rect = this.$refs.lookContainer.getBoundingClientRect()

      if (windowHeight - rect.top >= scrollHeight && this.isRefreshBool) {
        // console.log('距顶部' + scrollTop + '可视区高度' + windowHeight + '滚动条总高度' + scrollHeight, rect)
        // console.log(windowHeight - rect.top, scrollHeight)
        this.isRefreshBool = false
        this.showBottom = true
        if (this.current == this.pages) {
          this.loadingMore = false
        } else {
          this.loadingMore = true
          this.onLoadMore()
        }
      }
    },
    openDetail(productId) {
      this.$refs.goodInfoModal.show(productId, '')
    },
    openBigImg(list) {
      if (list.length == 0) return
      let result = list.map(i => i.url)
      this.imgList = result
      this.visibleImgs = true
    },
    // 关闭大图
    closeBig(value) {
      this.visibleImgs = value
      setTimeout(() => {
        this.imgList = []
      }, 100)
    },
    // look详情
    openLookDetail(item) {
      this.$refs.recommendLookDraw.show(item)
    },
    sendProduct(obj) {
      this.$emit('sendProduct', obj)
    },
    sendLook(obj) {
      this.$emit('sendLook', obj)
    },
    updateShoppingCart(value) {
      if (value) this.$emit('refreshShoppingCart', true)
    }
  }
}
</script>
<style lang="less" scoped src="../style/style.less"></style>
<style lang="less" scoped>
.ant-pro-pages-list-projects-cardList {
  margin-top: 12px;
  height: 100%;
  min-height: 200px;
  overflow-y: auto;
  /deep/ .ant-row {
    display: grid;
    justify-content: space-evenly;
    grid-template-columns: repeat(auto-fill, 172px);
    // grid-row-gap: 16px;
    grid-column-gap: 8px;
  }
  /deep/ .ant-row::before {
    content: '';
    width: 0;
    display: none;
  }
  /deep/ .ant-list-item {
    margin-bottom: 24px;
    .ant-card-hoverable {
      cursor: default;
    }
  }
  /deep/ .ant-card {
    width: 172px;
    position: relative;
    overflow: hidden;
    background: #f0f2f5;
  }
  /deep/ .ant-card-hoverable:hover {
    border: 1px solid #1890ff;
    box-shadow: 0 2px 8px rgb(0 0 0 / 30%);
  }
  /deep/ .ant-card-body {
    padding: 0 0 12px;
    position: relative;
    min-height: 234px;
  }
}
.bottom-tip {
  text-align: center;
  line-height: 100px;
  height: 100px;
  font-size: 14px;
}
.gallery {
  position: relative;
  .cover {
    width: 172px;
    height: 258px;
    display: block;
    object-fit: cover;
    cursor: pointer;
  }
  .four-imgs {
    width: 172px;
    height: 258px;
    display: flex;
    flex-wrap: wrap;
    cursor: pointer;
    background: #fff;
    img {
      width: 50%;
      height: 50%;
      object-fit: cover;
    }
  }
  .vertical,
  .horizontal {
    background: #d9d9d9;
    position: absolute;
    z-index: 2;
  }
  .vertical {
    width: 1px;
    height: 100%;
    left: 50%;
    top: 0;
  }
  .horizontal {
    height: 1px;
    width: 100%;
    top: 50%;
  }
  .rank {
    position: absolute;
    top: -4px;
    left: 0;
  }
  .magnifier {
    position: absolute;
    bottom: 0px;
    left: 0;
    width: 24px;
    height: 24px;
    cursor: pointer;
  }
  .code {
    position: absolute;
    bottom: 0px;
    right: 0;
    background: rgba(0, 0, 0, 0.5);
    height: 24px;
    line-height: 24px;
    color: #fff;
    font-size: 13px;
    font-family: PingFangSC-Regular, PingFang SC;
    font-weight: 400;
    padding: 0 8px;
  }
}
.thumb-content {
  padding: 8px 6px;
  display: flex;
  .thumb {
    margin-right: 8px;
    width: 48px;
    height: 48px;
    background: #fff;
    object-fit: scale-down;
    cursor: pointer;
  }
  .thumb:last-child {
    margin-right: 0px;
  }
}
.look-name {
  font-size: 14px;
  font-family: PingFangSC-Medium, PingFang SC;
  font-weight: 500;
  color: rgba(0, 0, 0, 0.85);
  margin-bottom: 8px;
  line-height: 24px;
}
.table-page-search-wrapper {
  /deep/.ant-form-item-label {
    padding-left: 24px;
  }
  /deep/.ant-col:first-child {
    .ant-form-item-label {
      padding-left: 0px;
    }
  }
}
</style>

